//
//  SWPasswordResetViewController.swift
//  MiU
//
//  Created by linhan on 16/3/26.
//  Copyright © 2016年 MiU. All rights reserved.
//

import Foundation
import UIKit
class SWPasswordResetViewController: SWBaseViewController,UITextFieldDelegate,SWAPIComponent
{
    //var verifyCode:String = ""
    //var phone:String = ""
    private var _intervalID:String = ""
    private var _smsSendTime:Double = 0
    lazy private var _getCodeBtn:UIButton = UIButton(type:.system)
    
    lazy private var _topView:UIView = UIView()
    lazy private var _telTextField:ImageTextField = ImageTextField()
    lazy private var _codeTextField:ImageTextField = ImageTextField()
    lazy private var _passwordTextField:ImageTextField = ImageTextField()
    
    private var _resetBtn:UIButton = UIButton(type:.system)
    
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
    }
    
    override func viewWillLayoutFirstTime() {
        setup()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if navigationController == nil
        {
            clearInterval(_intervalID)
        }
    }
    
    deinit
    {
        trace("DEINIT SWPasswordResetViewController")
    }
    
    //是否处于冷却中
    var inWaiting:Bool
        {
            return (SW.Config.GetVerifyCodeCDTime - ((NSDate().timeIntervalSince1970 - _smsSendTime))) > 0
    }
    
    //MARK ============================================================================================
    //==============================            Public Method           ===============================
    //=================================================================================================
    
    
    private func setup()
    {
        title = "忘记密码"
        view.backgroundColor = UIColor.white
        
        //输入时整个topview上移
        _topView.frame = CGRectMake(0, 0, view.width, 0)
        view.addSubview(_topView)
        
        let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
        view.addGestureRecognizer(tapGesture)
        
        let TextFieldWidth:CGFloat = view.width * 0.733
        let TextFieldHeight:CGFloat = 50
        let TextFieldLeftMargin:CGFloat = (view.width - TextFieldWidth) * 0.5
        let PlaceholderColor:UIColor = UIColor(hex: "0xababab")
        let InputColor:UIColor = UIColor.darkGray
        let TextFieldBorderColor:UIColor = UIColor(hex: 0xd0d0d0)
        
        //输入时整个topview上移
        _topView.frame = CGRectMake(0, navigationBarBottom + 44.0, view.width, 0)
        view.addSubview(_topView)
        
        //手机输入框
        _telTextField.frame = CGRectMake(TextFieldLeftMargin, 0, TextFieldWidth, TextFieldHeight)
        _telTextField.textInset = UIEdgeInsetsMake(0, 18, 0, 18)
        _telTextField.font = UIFont.systemFont(ofSize:14)
        _telTextField.textAlignment = .left
        _telTextField.keyboardType = .phonePad
        _telTextField.clearButtonMode = .whileEditing
        _telTextField.delegate = self
        _telTextField.attributedPlaceholder = NSMutableAttributedString(string: "请输入手机号码", attributes: [NSForegroundColorAttributeName:PlaceholderColor])
        _telTextField.textColor = InputColor
        _telTextField.layer.borderColor = TextFieldBorderColor.cgColor
        _telTextField.layer.borderWidth = 1
        _telTextField.layer.cornerRadius = 4
        _telTextField.layer.masksToBounds = true
        _topView.addSubview(_telTextField)
        
        //验证码
        let codeView = UIView()
        codeView.layer.borderColor = TextFieldBorderColor.cgColor
        codeView.layer.borderWidth = 1
        codeView.layer.cornerRadius = 4
        codeView.layer.masksToBounds = true
        codeView.frame = CGRectMake(TextFieldLeftMargin, _telTextField.bottom + 25, TextFieldWidth, TextFieldHeight)
        _topView.addSubview(codeView)
        
        let CodeButtonWidth:CGFloat = 100
        let CodeButtonHeight:CGFloat = TextFieldHeight
        _getCodeBtn.frame = CGRectMake(codeView.width - CodeButtonWidth, 0, CodeButtonWidth, CodeButtonHeight)
        _getCodeBtn.titleLabel?.font = UIFont.systemFont(ofSize:14)
        _getCodeBtn.setTitleColor(UIColor(hex:0xf4c4c1), for: .normal)
        _getCodeBtn.addTarget(self, action: #selector(getCodeBtnTapped), for: .touchUpInside)
        getCodeButtonEnabled = true
        codeView.addSubview(_getCodeBtn)
        
        let sepaLine:UIView = UIView()
        sepaLine.backgroundColor = UIColor(hex: 0xd0d0d0)
        sepaLine.frame = CGRectMake(_getCodeBtn.x, 8, 1, codeView.height - 16)
        codeView.addSubview(sepaLine)
        
        _codeTextField.frame = CGRectMake(0, 0, _getCodeBtn.x, TextFieldHeight)
        _codeTextField.textInset = UIEdgeInsetsMake(0, 19, 0, 0)
        _codeTextField.font = UIFont.systemFont(ofSize:14)
        _codeTextField.textAlignment = .left
        _codeTextField.keyboardType = .phonePad
        _codeTextField.delegate = self
        _codeTextField.attributedPlaceholder = NSMutableAttributedString(string: "输入验证码", attributes: [NSForegroundColorAttributeName:PlaceholderColor])
        _codeTextField.textColor = InputColor
        codeView.addSubview(_codeTextField)
        
        //密码
        _passwordTextField.frame = CGRectMake(TextFieldLeftMargin, codeView.bottom + 25, TextFieldWidth, TextFieldHeight)
        _passwordTextField.textInset = UIEdgeInsetsMake(0, 19, 0, 19)
        _passwordTextField.font = UIFont.systemFont(ofSize:14)
        _passwordTextField.textColor = InputColor
        _passwordTextField.isSecureTextEntry = true
        _passwordTextField.clearButtonMode = .whileEditing
        _passwordTextField.delegate = self
        _passwordTextField.layer.borderColor = TextFieldBorderColor.cgColor
        _passwordTextField.layer.borderWidth = 1
        _passwordTextField.layer.cornerRadius = 4
        _passwordTextField.layer.masksToBounds = true
        _passwordTextField.attributedPlaceholder = NSMutableAttributedString(string: "输入密码", attributes: [NSForegroundColorAttributeName:PlaceholderColor])
        _topView.addSubview(_passwordTextField)
        
        //注册
        _resetBtn.setTitleColor(UIColor.white, for: .normal)
        _resetBtn.titleLabel?.font = UIFont.systemFont(ofSize:18)
        _resetBtn.setTitle("重置密码", for: .normal)
        _resetBtn.backgroundColor = UIColor(hex: 0xf46363)
        _resetBtn.layer.cornerRadius = 4
        _resetBtn.layer.masksToBounds = true
        _resetBtn.frame = CGRectMake(TextFieldLeftMargin, _passwordTextField.bottom + 25, TextFieldWidth, 50)
        _resetBtn.addTarget(self, action: #selector(resetBtnTapped), for: .touchUpInside)
        _topView.addSubview(_resetBtn)
        
        _topView.height = _resetBtn.bottom
    }
    
    private var getCodeButtonEnabled:Bool = false {
        didSet
        {
            if getCodeButtonEnabled != oldValue
            {
                let imageName:String = getCodeButtonEnabled ? "auth_btn_login" : "auth_img_bg_input"
                _getCodeBtn.setBackgroundImage(UIImage(named:imageName)?.resizableImage(withCapInsets: UIEdgeInsetsMake(0, 19, 0, 19), resizingMode: .stretch), for: .normal)
                if getCodeButtonEnabled
                {
                    _getCodeBtn.setTitle("获取验证码", for: .normal)
                }
            }
        }
    }
    
    //获取验证码按钮重置
    private func verifyCodeButtonReset()
    {
        _smsSendTime = 0
        clearInterval(_intervalID)
        _getCodeBtn.setTitle("获取验证码", for: .normal)
        getCodeButtonEnabled = true
    }
    
    //更新获取按钮上的文字
    private func updateGetCodeBtn()
    {
        //30秒内只能发送一次
        let time:Double = SW.Config.GetVerifyCodeCDTime - ((NSDate().timeIntervalSince1970 - _smsSendTime))
        
        if time > 1
        {
            _getCodeBtn.setTitle("\(Int(time))秒后获取", for: .normal)
            getCodeButtonEnabled = false
        }
        else
        {
            clearInterval(_intervalID)
            getCodeButtonEnabled = true
        }
        
    }
    
    //发送请求以获取验证码
    private func getVerifyCode(tel:String)
    {
        let askCheckCodeReq:SWVerifyCodeFetchReq = SWVerifyCodeFetchReq()
        askCheckCodeReq.phone = tel
        askCheckCodeReq.action = .PasswordReset
        askCheckCodeReq.successCallback = {response,cache in
            SVProgressHUD.showSuccess(withStatus:"验证码已发送")
        }
        
        askCheckCodeReq.failCallback = {[weak self] error in
            self?.verifyCodeButtonReset()
            SVProgressHUD.showError(withStatus:error.message)
        }
        load(askCheckCodeReq)
    }
    
    //密码重置
    private func reset(phone:String, password:String, verify:String)
    {
        let req = SWPasswodRestReq()
        req.password = password
        req.phone = phone
        req.verifyCode = verify
        req.successCallback = {[weak self] response,cache in
            self?.resetSuccess(phone: phone, password:password)
        }
        req.failCallback = {[weak self] error in
            self?.resetFail(error)
        }
        load(req)
    }
    
    private func resetSuccess(phone:String, password:String)
    {
        SVProgressHUD.showSuccess(withStatus:"密码修改成功")
        if let viewControllers = navigationController?.viewControllers , viewControllers.count > 0
        {
            for i in 0..<viewControllers.count
            {
                if let loginViewController = viewControllers[i] as? SWLoginViewController
                {
                    loginViewController.phone = phone
                    loginViewController.password = password
                    loginViewController.autoLogin = true
                    navigationController?.popToViewController(loginViewController, animated: false)
                    break
                }
            }
        }
    }
    
    private func resetFail(_ error:NSError)
    {
        let errorCode = error.code
        if errorCode == SWErrorCode.VERIFY_CODE_Invalid
        {
            verifyCodeButtonReset()
        }
        _resetBtn.isEnabled = true
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
    {
        var inputEnable:Bool = true
        if textField == _telTextField
        {
            //手机号限制只能输入20个以内的数字
            let MaxCount:Int = 20
            inputEnable = string == "" || ((textField.text?.length ?? 0) + string.length < MaxCount && Regex("^[\\d-]+$").test(string))
        }
        return inputEnable
    }
    
//    func textFieldDidBeginEditing(textField: UITextField)
//    {
//        UIView.animate(withDuration:0.3, animations: {
//            self._topView.y = 0
//        })
//    }
    
    //MARK ============================================================================================
    //==============================               Selector             ===============================
    //=================================================================================================
    
    
    @objc private func getCodeBtnTapped()
    {
        let tel:String = _telTextField.text ?? ""
        if tel == ""
        {
            SVProgressHUD.showError(withStatus:"输入手机号码")
            return
        }
        if inWaiting
        {
            return
        }
        _smsSendTime = NSDate().timeIntervalSince1970
        
        getVerifyCode(tel: tel)
        clearTimeout(self._intervalID)
        _intervalID = setInterval(1, closure: {
            self.updateGetCodeBtn()
        })
        updateGetCodeBtn()
    }
    
    @objc private func resetBtnTapped()
    {
        guard let tel = _telTextField.text , tel != "" else
        {
            SVProgressHUD.showError(withStatus:"输入手机号码")
            return
        }
        guard let code = _codeTextField.text , code != "" else
        {
            SVProgressHUD.showError(withStatus:"输入验证码")
            return
        }
        guard let password1 = _passwordTextField.text , password1 != "" else
        {
            SVProgressHUD.showError(withStatus:"输入密码")
            return
        }
        
        reset(phone: tel, password:password1, verify:code)
        SVProgressHUD.show(withStatus:"密码修改中...")
        _resetBtn.isEnabled = false
    }
    
    //点击空白区域，内容下移
    @objc private func viewTapped()
    {
        view.endEditing(true)
    }
    
}
